/**
 * 音频相关API接口
 */

import type {
  AudioDetailResponse,
  AudioFavoriteReqVO,
  AudioFavoriteResponse,
  AudioFavoriteStatusResponse,
  AudioPlayRecordResponse,
  AudioPlayReqVO,
  AudioResourceRespVO,
  AudioSearchParams,
  AudioSearchResponse,
  BatchAudioFavoriteCheckReqVO,
  BatchAudioFavoriteStatusResponse,
  ClearPlayRecordsParams,
  PlayRecordListResponse,
  RecentAudioParams,
  RecentAudioResponse,
  RecommendedAudioParams,
  RecommendedAudioResponse,
} from './types/audio'
import type { ApiResponse, PageResult } from './types/common'
import { http } from '@/utils/request'

// ==================== 音频分类管理 ====================

/**
 * 获取音频分类列表
 */
export function getAudioCategories(language?: string) {
  // 返回固定的音频分类，包括特殊分类和数据库分类
  const fixedCategories = [
    { key: 'recent', label: '最近', icon: 'clock', isSpecial: true },
    { key: 'favorite', label: '收藏', icon: 'heart', isSpecial: true },
  ]

  // 语言分类
  const languageCategories = [
    { key: 'english', label: '英文', icon: 'globe', isSpecial: false },
    { key: 'chinese', label: '中文', icon: 'globe', isSpecial: false },
  ]

  return Promise.resolve({
    code: 200,
    data: [...fixedCategories, ...languageCategories],
    message: 'success',
  })
}

// ==================== 音频列表和搜索 ====================

/**
 * 获取音频资源列表
 */
export function getAudioList(params: {
  category: string
  lang?: string
  limit?: number
}) {
  return http.get<ApiResponse<AudioResourceRespVO[]>>('/reading/audio/list', params)
}

/**
 * 搜索音频资源
 */
export function searchAudio(params: AudioSearchParams) {
  return http.get<AudioSearchResponse>('/reading/audio/search', params)
}

/**
 * 获取推荐音频资源
 */
export function getRecommendedAudio(params?: RecommendedAudioParams) {
  return http.get<RecommendedAudioResponse>('/reading/audio/recommended', params)
}

/**
 * 获取音频详情
 */
export function getAudioDetail(audioId: number) {
  return http.get<AudioDetailResponse>(`/reading/audio/${audioId}`)
}

// ==================== 播放记录管理 ====================

/**
 * 保存音频播放记录
 */
export function saveAudioPlayRecord(data: AudioPlayReqVO) {
  return http.post<AudioPlayRecordResponse>('/reading/audio/play', data)
}

/**
 * 获取最近播放的音频
 */
export function getRecentPlayAudio(params?: RecentAudioParams) {
  return http.get<RecentAudioResponse>('/reading/audio/recent', params)
}

/**
 * 获取播放记录列表
 */
export function getPlayRecordList(params: { page?: number, size?: number }) {
  return http.get<PlayRecordListResponse>('/reading/audio/play-records', params)
}

/**
 * 清空播放记录
 */
export function clearPlayRecords(params?: ClearPlayRecordsParams) {
  return http.delete<ApiResponse<boolean>>('/reading/audio/clear', params)
}

/**
 * 删除单个音频播放记录
 */
export function deleteAudioPlayRecord(audioId: number) {
  return http.delete<ApiResponse<boolean>>(`/reading/audio/play-record/${audioId}`)
}

// ==================== 关联内容音频 ====================

/**
 * 获取绘本相关音频
 */
export function getBookAudio(bookId: number) {
  return http.get<RecommendedAudioResponse>(`/reading/audio/book/${bookId}`)
}

/**
 * 获取绘本集相关音频
 */
export function getBookSetAudio(bookSetId: number) {
  return http.get<RecommendedAudioResponse>(`/reading/audio/book-set/${bookSetId}`)
}

// ==================== 音频收藏功能 ====================

/**
 * 添加音频收藏
 */
export function addAudioFavorite(data: AudioFavoriteReqVO) {
  return http.post<AudioFavoriteResponse>('/reading/favorites/add', {
    targetType: 'audio',
    targetId: data.audioId,
    remark: data.remark,
  })
}

/**
 * 取消音频收藏
 */
export function removeAudioFavorite(audioId: number) {
  return http.post<AudioFavoriteResponse>('/reading/favorites/remove', {
    targetType: 'audio',
    targetId: audioId,
  })
}

/**
 * 切换音频收藏状态
 */
export function toggleAudioFavorite(audioId: number, remark?: string) {
  // 构建查询参数对象
  const queryParams: Record<string, string> = {
    targetType: 'audio',
    targetId: audioId.toString(),
  }

  // 如果有备注，添加到参数中
  if (remark) {
    queryParams.remark = remark
  }

  // 使用 http.post 的第三个参数传递查询参数
  return http.post<AudioFavoriteResponse>('/reading/favorites/toggle', undefined, queryParams)
}

/**
 * 检查音频收藏状态
 */
export function checkAudioFavoriteStatus(audioId: number) {
  return http.get<AudioFavoriteStatusResponse>('/reading/favorites/check', {
    targetType: 'audio',
    targetId: audioId,
  })
}

/**
 * 批量检查音频收藏状态
 */
export function batchCheckAudioFavoriteStatus(data: BatchAudioFavoriteCheckReqVO) {
  return http.post<BatchAudioFavoriteStatusResponse>('/reading/favorites/batch-check', {
    items: data.audioIds.map(audioId => ({
      targetType: 'audio',
      targetId: audioId,
    })),
  })
}

/**
 * 获取收藏的音频列表
 */
export function getFavoriteAudioList(params: { page?: number, size?: number }) {
  return http.get<ApiResponse<PageResult<any>>>('/reading/favorites/audios', params)
}

// ==================== 音频点赞功能 ====================

/**
 * 点赞音频
 */
export function likeAudio(audioId: number) {
  return http.post<ApiResponse<boolean>>(`/reading/audio/${audioId}/like`)
}

/**
 * 取消点赞音频
 */
export function unlikeAudio(audioId: number) {
  return http.delete<ApiResponse<boolean>>(`/reading/audio/${audioId}/like`)
}

// ==================== 工具函数 ====================

/**
 * 格式化音频时长
 * @param seconds 秒数
 * @returns 格式化的时长字符串 (如: "05:23")
 */
export function formatAudioDuration(seconds: number): string {
  if (!seconds || seconds < 0)
    return '00:00'

  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = Math.floor(seconds % 60)

  return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
}

/**
 * 解析音频时长文本
 * @param durationText 时长文本 (如: "05:23")
 * @returns 总秒数
 */
export function parseAudioDuration(durationText: string): number {
  if (!durationText)
    return 0

  const parts = durationText.split(':')
  if (parts.length !== 2)
    return 0

  const minutes = Number.parseInt(parts[0], 10) || 0
  const seconds = Number.parseInt(parts[1], 10) || 0

  return minutes * 60 + seconds
}

/**
 * 获取音频分类的显示文本
 * @param category 音频分类
 * @returns 显示文本
 */
export function getAudioCategoryText(category: string): string {
  const categoryMap: Record<string, string> = {
    all: '全部',
    recent: '最近播放',
    english: '英文',
    chinese: '中文',
    favorite: '收藏',
  }

  return categoryMap[category] || category
}

/**
 * 检查音频是否可以播放
 * @param audio 音频对象
 * @returns 是否可以播放
 */
export function isAudioPlayable(audio: AudioResourceRespVO): boolean {
  return !!(audio && audio.audioUrl && audio.enabled !== false)
}

/**
 * 获取音频封面图片URL
 * @param audio 音频对象
 * @returns 封面图片URL
 */
export function getAudioCoverUrl(audio: AudioResourceRespVO): string {
  return audio.cover || '/static/images/default-audio-cover.png'
}
